//
//  DPMeWalletViewController.swift
//  DoctorEPlus
//
//  Created by 王林波 on 2021/3/8.
//

import UIKit
import IDealist

class DPMeWalletViewController: BHBaseViewController {

    lazy var tableView: UITableView = {
        let view = UITableView.buildTableView(style: .plain)
        
        view.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: UIScreen.showHeight)
        view.register(UINib.init(nibName: "DPWalletOperationCell", bundle: nil), forCellReuseIdentifier: "DPWalletOperationCell")
        view.register(UINib.init(nibName: "DPComEmptyCell", bundle: nil), forCellReuseIdentifier: "DPComEmptyCell")
        view.delegate = self
        view.dataSource = self
        return view
    }()
    
    lazy var headerView: DPMeWalletHeaderView = {
        let view = DPMeWalletHeaderView.loadFromXib()
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: DPMeWalletHeaderView.headerHeight)
        return view
    }()
    

    lazy var walletManager: DPWalletFlowManager = {
        let manager = DPWalletFlowManager.init()
        return manager
    }()
    
    var flowArray: [DPWalletFlowModel] = []
    
    // 账号信息
    fileprivate var accountModel = DPWalletAlipayInfoModel.init()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.page = 1
        self.loadMyBalanceService()
        self.loadAllOutInFlowService()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.bh_navigationBar.title_label.text = "钱包"
        
        self.view.addSubview(self.tableView)
        self.tableView.tableHeaderView = self.headerView
        
        self.headerView.headerDidSelectIndexBlock = { [weak self] index in
            if index ==  0{
                let withDrawVC = DPMeWalletWithDrawViewController.init()
                self?.navigationController?.pushViewController(withDrawVC, animated: true)
            }else {
                let allBillVC = DPWalletBillBaseViewController.init()
                self?.navigationController?.pushViewController(allBillVC, animated: true)
            }
        }
        
        
        
        // 加载
        self.tableView.addloadMore { [weak self] in
            self?.page += 1
            self?.loadAllOutInFlowService()
        }
        
        self.bh_navigationBar.rightBtn.isHidden = false
        self.bh_navigationBar.rightBtn.setTitle("账户", for: .normal)
    }
    
    override func rightBtnAction() {
        let accountVC = DPWalletAccoutViewController.init()
        accountVC.alipayAccountModel = self.accountModel
        self.navigationController?.pushViewController(accountVC, animated: true)
    }
  

}
extension DPMeWalletViewController: UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        if self.flowArray.count == 0 {
            return 0
        }
        return self.flowArray.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.flowArray.count == 0 {
            return 0
        }
        let model = self.flowArray[section]
        return model.itemArray.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if self.flowArray.count == 0 {
            return 500
        }
        return DPWalletOperationCell.cellHeight
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if self.flowArray.count == 0 {
            return 0
        }
        return DPMeWalletOutInSecView.height
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if self.flowArray.count == 0 {
            return nil
        }
        let model = self.flowArray[section]

        let  view = DPMeWalletOutInSecView.loadFromXib()
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: DPMeWalletOutInSecView.height)
        view.date_label.text = model.month
        view.in_label.text = "收入 ¥"+model.inTotalAmount
        view.out_label.text = "转出 ¥"+model.outTotalAmount
        return view
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        if self.flowArray.count == 0 {
//            let cell = tableView.dequeueReusableCell(withIdentifier: "DPComEmptyCell", for: indexPath) as! DPComEmptyCell
//            cell.iconStartY.constant = 100
//            cell.emptyImageView.image = UIImage.empty_for_list
//            cell.empty_desLabel.text = "暂无账单信息"
//            return cell
//        }
        let cell = tableView.dequeueReusableCell(withIdentifier: "DPWalletOperationCell", for: indexPath) as! DPWalletOperationCell
        let model = self.flowArray[indexPath.section]
        let itemModel = model.itemArray[indexPath.row]
        cell.model = itemModel
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if self.flowArray.count == 0 {
            return
        }
        let detailVC = DPWalletFlowDetailViewController.init()
        let model = self.flowArray[indexPath.section]
        let itemModel = model.itemArray[indexPath.row]
        detailVC.model = itemModel
        self.navigationController?.pushViewController(detailVC, animated: true)
    }
}


extension  DPMeWalletViewController {
    // 获取我的余额
    func loadMyBalanceService() {
        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        manager.get(url: String.wallet_user_account_url, paramters: [:]) { (success, errorMsg, responseDic) in
            SVProgressHUD.dismiss()

            if success == true {
                let dic = BHJsonTool.decodeDicFromDic(dic: responseDic, key: "result")
                self.accountModel.parseDic(dic)
                self.headerView.money_label.text = self.accountModel.balance
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
    
    // 所有收支流水
    func loadAllOutInFlowService() {
        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        manager.get(url: String.wallet_user_billDetail_url, paramters: ["current":self.page,"pageSize":"20","type":"0"]) { (success, errorMsg, responseDic) in
            SVProgressHUD.dismiss()
            if success == true {
                let result = BHJsonTool.decodeDicFromDic(dic: responseDic, key: "result")
                let totalCount = BHJsonTool.decodeIntFromDic(dic: result, key: "total")
                
                let records = BHJsonTool.decodeArrayFromDic(dic: result, key: "records")
                if self.page == 1 {
                    self.tableView.endLoadWithNoMoreData(false)
                    if self.flowArray.count != 0 {
                        self.flowArray.removeAll()
                    }
                }
                self.walletManager.analyzeFlow(existArray: self.flowArray, appendArray: records) {[weak self] ( result, total) in
                    self?.flowArray = result
                    DispatchQueue.main.async {
                        self?.tableView.reloadData()
                        self?.tableView.endRefresh()
                        self?.tableView.endLoading()
                        
                        self?.tableView.endLoadWithNoMoreData(total >= totalCount)
                        self?.tableView.mj_footer?.isHidden = self?.flowArray.count == 0
                    }
                }
                
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
    
}

